import { addMcp, apiInterceptors, listMcp, updateMcp } from '@/client/api';
import { useRequest } from 'ahooks';
import { App, ConfigProvider, Divider, Form, Input, Modal, Spin,Upload } from 'antd';
import Icon, { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import Image from 'next/image';
import { ChatContext } from '@/app/chat-context';
import React, { useContext,useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import styles from './styles.module.css';
import { env } from 'process';

interface WorkModeSelectProps {
  disable: boolean;
  options: Array;
  value?: Array;
  onChange?: (value: any) => void;
}

// 自定义方式
const WorkModeSelect: React.FC<WorkModeSelectProps> = ({ disable = false, options = [], value, onChange }) => {

  const [selected, setSelected] =  useState(value || {});

  const returnOptionStyle = (item: any) => {
    if (disable) {
      return classNames(
        `flex items-center p-4 border rounded-lg border-[#d9d9d9]  cursor-not-allowed relative transition-all duration-500 ease-in-out`,
        {
          'bg-[rgba(0,0,0,0.04)] dark:bg-[#606264]': item.value === selected,
        },
      );
    }
    return `flex items-center p-4  border dark:border-[rgba(217,217,217,0.85)] rounded-lg cursor-pointer hover:border-[#8665FF] hover:bg-[#f5faff] dark:hover:border-[rgba(12,117,252,0.85)] dark:hover:bg-[#606264] relative transition-all duration-300 ease-in-out ${
      item.value === selected
        ? 'border-[#8665FF] bg-[#f5faff] dark:bg-[#606264] dark:border-[#8665FF]'
        : 'border-[#d9d9d9]'
    } `;
  };

  return (
    <div className='grid grid-cols-2 gap-4'>
      {options.map(item => (
        <div
          className={returnOptionStyle(item)}
          key={item.value}
          onClick={() => {
            if (disable) {
              return;
            }
            setSelected(item.value);
            onChange?.({ type:item.value });
          }}
        >
          <Image src={`/icons/mcp/${item.value}.png`} width={48} height={48} alt={item.value} />
          <div className='flex flex-col ml-3'>
            <span className='text-xs font-medium text-[rgba(0,0,0,0.85)] dark:text-[rgba(255,255,255,0.85)] first-line:leading-6'>
              { item.name }
            </span>
            <span className='text-xs text-[rgba(0,0,0,0.45)] dark:text-[rgba(255,255,255,0.85)]'>
              { item.description }
            </span>
          </div>
          {item.value === selected && (
            <div
              className='w-3 h-3 rounded-tr-md absolute top-[1px] right-[1px] transition-all duration-300 ease-in-out'
              style={{
                background: `linear-gradient(to right top, transparent 50%, transparent 50%, ${disable ? '#d0d0d0' : '#8665FF'} 0)`,
              }}
            />
          )}
        </div>
      ))}
    </div>
  );
};

const CreateAppModal: React.FC<{
  open: boolean;
  onCancel: () => void;
  refresh?: any;
  type?: 'add' | 'edit';
}> = ({ open, onCancel, type = 'add', refresh }) => {
  const { t } = useTranslation();
  const { userInfo } = useContext(ChatContext);

  const mcpInfo = JSON.parse(localStorage.getItem('new_mcp_info') || '{}');
  mcpInfo.args =  typeof mcpInfo.args === 'string' && mcpInfo.args
  ? mcpInfo.args.replace(/,/g, '\n')
  : '';
  mcpInfo.env = convertFromJson(mcpInfo.env);

  const { message } = App.useApp();
  const [form] = Form.useForm();
  const mcpType = Form.useWatch('type', form)

  // 将 KEY1=value1\nKEY2=value2 格式转为 JSON 字符串
  function convertToJson(text) {
      const result = {};
      text.split('\n')
          .filter(line => line.trim() !== '')
          .forEach(line => {
              const separatorIndex = line.indexOf('=');
              if (separatorIndex !== -1) {
                  const key = line.substring(0, separatorIndex);
                  const value = line.substring(separatorIndex + 1);
                  result[key] = value;
              }
          });
      return JSON.stringify(result, null, 2);
  }

  // 将 JSON 字符串转回 KEY1=value1\nKEY2=value2 格式
  function convertFromJson(jsonString) {
      try {
          const obj = JSON.parse(jsonString);
          return Object.entries(obj)
              .map(([key, value]) => `${key}=${value}`)
              .join('\n');
      } catch (error) {
          console.error('Invalid JSON format:', error);
          return '';
      }
  }
  
  const modeOptions = [
    {
      name: '服务器发送事件(sse)',
      value: 'sse',
      description: ''
    },
    {
      name: '可流式传输的HTTP(streamableHttp)',
      value: 'http',
      description: ''
    },
    {
      name: '标准输入/输出(stdio)',
      value: 'stdio',
      description: ''
    }
  ]
  
  // 创建mcp
  const { run: createApp, loading: createLoading } = useRequest(
    async (params: any) => {   
      const paramsData = params;
      paramsData.args = params.args ? params.args.replace(/\n/g, ',') : '';
      paramsData.env = convertToJson(params.env);
      if(paramsData.type==2){
        delete paramsData.server_url;
        delete paramsData.server_headers;
      }

      if (type === 'edit') {
        return await apiInterceptors(
          updateMcp({
            id: mcpInfo.id,
            creator: userInfo.sub || userInfo.login_name,
            ...paramsData,
          }),
        );
      } else {
        return await apiInterceptors(
          addMcp({
            ...paramsData,
            creator: userInfo.sub || userInfo.login_name,
          }),
        );
      }
    },
    {
      manual: true,
      onSuccess: async res => {
        const [error, data] = res;
        if (!error) {
          if (type === 'edit') {
            const [, res] = await apiInterceptors(listMcp({}));
            const curMcp = res?.data?.find(item => item.id === mcpInfo?.id);
            localStorage.setItem('new_mcp_info', JSON.stringify({ ...curMcp, isEdit: true }));
            message.success(t('Update_successfully'));
            onCancel();
          } else {
            if(data){
              message.success(t('Create_successfully'));
              localStorage.setItem('new_mcp_info', JSON.stringify(data));
              onCancel();        
            }
          }
        } else {
          message.error(type === 'edit' ? t('Update_failure') : t('Create_failure'));
        }
        await refresh?.()
      }
    }
  )
  return (
    <ConfigProvider
      theme={{
        components: {
          Button: {
            defaultBorderColor: '#d9d9d9',
          },
        },
      }}
    >
      <Modal
        className={styles['create-app-modal-container']}
        title={type==='add'?t('create') +t('mcp'): t('Edit')+t('mcp')}
        width={800}
        open={open}
        onOk={async () => {
          form.validateFields().then(async (values: any) => {
            await createApp({
              name: values?.name,
              desc: values?.desc,
              type: values?.type === 'sse'? 0 : values?.type === 'http'? 1 : 2,    
              server_url: values?.server_url,
              server_headers: values.server_headers || '{}',
              script: values?.script || '',
              args: values?.args || '',
              env: values?.env || '',        
            });
          });
        }}
        onCancel={onCancel}
        centered={true}
      >
        <Spin spinning={createLoading}>
          <div className='flex flex-1'>
            <Form
              layout='vertical'
              className='w-full'
              form={form}
              initialValues={{
                type: mcpInfo.type == 1 ? 'http': mcpInfo.type == 2 ? 'stdio' : 'sse',
                name: mcpInfo?.name,
                desc: mcpInfo?.desc,
                server_url: mcpInfo?.server_url,
                server_headers: mcpInfo?.server_headers,
                script: mcpInfo?.script || '',
                args: mcpInfo?.args || '',
                env: mcpInfo?.env || '',       
              }}
            >
              <Form.Item
                label={t('mcp_mode')}
                name='type'
                required
                rules={[{ required: true, message: ''}]}
              >
                <WorkModeSelect 
                  options={modeOptions || []} 
                  value={form.getFieldValue('type')}
                  onChange={val => {                
                    form.setFieldsValue({
                      type: val.type,
                      name: "",
                      desc: "",
                      server_url: "",
                      server_headers: "",
                    });
                  }}
                />
              </Form.Item>           
              <Form.Item
                label={`${t('mcp_name')}：`}
                name='name'
                required
                rules={[{ required: true, message: t('Please_Input') }]}
              >
                <Input placeholder={t('Please_Input')} autoComplete='off' className='h-8' />
              </Form.Item>
              { mcpType !== 'stdio' && (
                <>
                  <Form.Item
                    label={`${t('mcp_url')}：`}
                    name='server_url'
                    required
                    rules={[{ required: true, message: t('Please_Input') }]}
                  >
                    <Input placeholder={t('Please_Input')} autoComplete='off' className='h-8' />
                  </Form.Item>
                  <Form.Item
                    label={`${t('request_header')}：`}
                    name='server_headers'              
                  >
                    <Input.TextArea autoSize={{ minRows: 2.5 }} placeholder="Content-Type-application/jsonAuthorization-Bearer token" autoComplete='off' className='h-8' />
                  </Form.Item>
                </>
              )}
              { mcpType === 'stdio' && (
                <>
                  <Form.Item
                    label="命令"
                    name='script'     
                    required
                    rules={[
                      {
                        required: true,
                        message: "请输入命令",
                      }
                    ]}         
                  >
                    <Input.TextArea autoSize={{ minRows: 2 }} placeholder="示例:npx" autoComplete='off' className='h-8' />
                  </Form.Item>
                  <Form.Item
                    label="参数"
                    name='args'   
                    tooltip="每个参数占一行"                   
                  >
                    <Input.TextArea autoSize={{ minRows: 2.5 }} placeholder={`-y\nhowtocook-mcp`} autoComplete='off' className='h-8' />
                  </Form.Item>
                  <Form.Item
                    label="环境变量"
                    name='env'           
                    tooltip="格式:KEY=value,每行一个"                    
                  >
                    <Input.TextArea autoSize={{ minRows: 2.5 }} placeholder={`KEY1=value1\nKEY2=value2`} autoComplete='off' className='h-8' />
                  </Form.Item>
                </>
              )}
              <Form.Item
                label={`${t('server_info')}：`}
                name='desc'
                required
                rules={[
                  {
                    required: true,
                    message: t('placeholder_mcp_description'),
                  },
                ]}
              >
                <Input.TextArea
                  autoComplete='off'
                  placeholder=''
                  showCount 
                  maxLength={200}
                  autoSize={{ minRows: 2.5 }}
                />
              </Form.Item>          
            </Form>
          </div>
        </Spin>
      </Modal>
    </ConfigProvider>
  );
};

export default CreateAppModal;
